<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      :show-qk="showQk"
      @handleQuery="getDataList"
    >
      <template v-if="meta.indexOf('StatisticsBalanceExportShop') > -1" #btns>
        <el-button :loading="exportLoading" type="primary" @click="exportExcel">导出</el-button>
      </template>
    </QueryForm>
    <div class="doumee-filter">
      <div class="margin-t-10 statics-info-li">
        <span class="title">收支总额：</span>
        <span class="content">{{ subtotalCountVo.countMoneyOne }}</span>
        <span>元</span>
      </div>
      <div class="margin-t-10 statics-info-li">
        <span class="title">现款收支总额：</span>
        <span class="content">{{ subtotalCountVo.countMoneyThree }}</span>
        <span>元</span>
      </div>
      <div class="margin-t-10 statics-info-li">
        <span class="title">会员收支总额：</span>
        <span class="content">{{ subtotalCountVo.countMoneyTwo }}</span>
        <span>元</span>
      </div>
    </div>
    <div class="doumee-table-buttons" />
    <el-table
      ref="tableRef"
      v-loading="listLoading"
      :data="list"
      border
      fit
      show-summary
      :summary-method="getSummaries"
      :header-row-class-name="'table-header'"
      class="doumee-element-table table_tj"
    >
      <el-table-column
        v-for="(item, index) in headList"
        :key="index"
        :prop="item.code"
        :label="item.name"
        show-overflow-tooltip
        :min-width="item.length?item.length: ''"
        align="center"
      >
        <el-table-column
          v-for="(em, dex) in item.nameVo"
          :key="dex"
          :prop="em.code"
          :label="em.name"
          :min-width="em.length?em.length: ''"
          show-overflow-tooltip
          align="center"
        />
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// import FileSaver from 'file-saver'
// import XLSX from 'xlsx'
// import { parseTime } from '@/utils/index'
import { venueList, tabelHead, sjList, StatisticsBalanceExportShop } from '@/api'
import dayjs from 'dayjs'
import { queryFormConfig } from './config'
export default {
  name: 'BusinessStatistics',
  data() {
    return {
      venueList: [],
      showQk: false,
      listLoading: false,
      queryFormConfig,
      list: [],
      headList: [],
      pagination: {
        page: 1,
        rows: 10
      },
      filters: {},
      meta: [],
      exportLoading: false,
      subtotalCountVo: {}
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.init()
  },
  methods: {
    init() {
      let time = []
      const start = new Date()
      const end = new Date()
      time = [dayjs(start).format('YYYY-MM-DD'), dayjs(end).format('YYYY-MM-DD')]
      this.$set(this.filters, 'time', time)
      this.getVenueList()
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index === 1) {
          sums[index] = '-'
        } else if (index === 2) {
          sums[index] = '-'
        }  else {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2)
          } else if (column.property.includes('.')) {
            let nums = 0
            data.forEach(s => {
              if (s.dataMap && s.dataMap[column.property.substring(column.property.lastIndexOf('\.') + 1, column.property.length)]) {
                if (!isNaN(s.dataMap[column.property.substring(column.property.lastIndexOf('\.') + 1, column.property.length)])) {
                  nums = nums + s.dataMap[column.property.substring(column.property.lastIndexOf('\.') + 1, column.property.length)]
                }
              }
            })
            sums[index] = nums.toFixed(2)
          } else {
            sums[index] = '-'
          }
        }
      })

      return sums
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        var rowm = this.mergeList[rowIndex] - rowIndex
        var rowidx = this.mergeIndexList[rowIndex]
        if (rowIndex === rowidx) {
          return {
            rowspan: rowm,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
    },
    getHeadList() {
      tabelHead({
        param: {
          headType: 'statistics'
        }
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.headList = res.recordList
            this.getDataList()
          }
        })
    },
    getDataList() {
      const { filters } = this
      this.listLoading = true
      sjList({
        param: {
          startTime: filters.time ? filters.time[0].slice(0, 10) + ' 00:00:00' : '',
          endTime: filters.time ? filters.time[1].slice(0, 10) + ' 23:59:59' : '',
          venueId: filters.venueId,
          headVos: this.headList
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.record.projectData
            this.subtotalCountVo = res.record
            this.$refs.tableRef.doLayout()
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 获取场馆列表
    getVenueList() {
      venueList({
        param: { flag: '0' }
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.venueList = res.recordList
            // this.$set(this.filters, 'venueId', res.recordList[0].id)
            const arr = res.recordList
            this.queryFormConfig.formItems[0].options = arr
            this.getHeadList()
          }
        })
    },
    // exportExcel() {
    //   const time = new Date().getTime()
    //   const filename = '营业结算统计' + time + '.xlsx'
    //   var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
    //   var wb = XLSX.utils.table_to_book(
    //     document.querySelector('.doumee-element-table'),
    //     xlsxParam
    //   )
    //   var wbout = XLSX.write(wb, {
    //     bookType: 'xlsx',
    //     bookSST: true,
    //     type: 'array'
    //   })
    //   try {
    //     FileSaver.saveAs(
    //       new Blob([wbout], { type: 'application/octet-stream' }),
    //       filename
    //     )
    //   } catch (e) {
    //     if (typeof console !== 'undefined') {
    //       console.log(e, wbout)
    //     }
    //   }
    // }
    exportExcel() {
      const { filters } = this
      this.exportLoading = true
      StatisticsBalanceExportShop({
        param: {
          startTime: filters.time ? filters.time[0].slice(0, 10) + ' 00:00:00' : '',
          endTime: filters.time ? filters.time[1].slice(0, 10) + ' 23:59:59' : '',
          venueId: filters.venueId,
          headVos: this.headList
        }
      })
        .then((res) => {
          this.exportLoading = false
          if (res.errorCode === '000000') {
            window.open(res.record.showUrl, '_blank')
          }
        })
        .catch(() => { this.exportLoading = false })
    }
    // exportExcel() {
    //   const time = new Date().getTime()
    //   const filename = '营业结算统计' + time + '.xlsx'
    //   const user = this.$store.state.app.user
    //   const param = this.filters
    //   var aoa = []
    //   const headList = [...this.headList]
    //   if (param.time && param.time.length > 0) {
    //     aoa = [
    //       ['#查询起始日期：' + param.time[0].slice(0, 10) + ' 00:00:00' + '查询终止日期' + param.time[1].slice(0, 10) + ' 23:59:59']
    //     ]
    //   }
    //   const workbook = XLSX.utils.book_new()
    //   var bottom = [
    //     ['#导出时间：' + parseTime(new Date())],
    //     ['#账号：' + user.userName + ' -' + user.realName]
    //   ]
    //   // 创建工作簿
    //   var table_dom = this.$refs['tableRef'].$el
    //   const new_sheet = XLSX.utils.table_to_sheet(table_dom)
    //   const a = XLSX.utils.sheet_to_json(new_sheet, { header: 1 })
    //   aoa = aoa.concat(a).concat(bottom)
    //   const merges = []
    //   let dex = 0
    //   const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']
    //   let obj = ''
    //   let name = {}
    //   headList.forEach((e, index) => {
    //     if (e.nameVo && e.nameVo.length > 0) {
    //       if (dex === 0) {
    //         dex = dex + index
    //         merges.push({ e: { c: dex, r: 1 }, s: { c: Number(dex) + Number(e.nameVo.length) - 1, r: 1 }})
    //         dex = Number(dex) + Number(e.nameVo.length)
    //       } else {
    //         obj = arr[dex] + '2'
    //         merges.push({ e: { c: dex, r: 1 }, s: { c: Number(dex) + Number(e.nameVo.length) - 1, r: 1 }})
    //         name = { t: 's', v: e.name }
    //         dex = Number(dex) + Number(e.nameVo.length)
    //       }
    //     } else {
    //       merges.push({ e: { r: 1, c: index }, s: { r: 2, c: index }})
    //     }
    //   })
    //   const worksheet = XLSX.utils.json_to_sheet(aoa, { skipHeader: true })
    //   worksheet[obj] = name
    //   worksheet['!merges'] = merges
    //   let aaa = worksheet['D3']
    //   let bbb = worksheet['E3']
    //   let ccc = worksheet['F3']
    //   worksheet['D3'] = bbb
    //   worksheet['E3'] = ccc
    //   worksheet['F3'] = aaa
    //   let index = 0
    //   const listObj = [...this.list]
    //   listObj.forEach((s, dex) => {
    //     index = dex + 4
    //     aaa = worksheet['D' + index]
    //     bbb = worksheet['E' + index]
    //     ccc = worksheet['F' + index]
    //     worksheet['D' + index] = bbb
    //     worksheet['E' + index] = ccc
    //     worksheet['F' + index] = aaa
    //   })
    //   const zjIndex = listObj.length + 4
    //   aaa = worksheet['D' + zjIndex]
    //   bbb = worksheet['E' + zjIndex]
    //   ccc = worksheet['F' + zjIndex]
    //   worksheet['D' + zjIndex] = bbb
    //   worksheet['E' + zjIndex] = ccc
    //   worksheet['F' + zjIndex] = aaa
    //   XLSX.utils.book_append_sheet(workbook, worksheet, filename)
    //   const wbout = XLSX.write(workbook, {
    //     bookType: 'xlsx',
    //     bookSST: true,
    //     type: 'array'
    //   })
    //   try {
    //     FileSaver.saveAs(
    //       new Blob([wbout], {
    //         type: 'application/octet-stream;charset=utf-8"'
    //       }), filename)
    //   } catch (e) {
    //     // if (typeof console !== 'undefined') console.log(e, wbOut)
    //   }
    //   return wbout
    // }
  }
}
</script>
<style scoped lang="scss">
@import '@/styles/variables.scss';
.doumee-filter {
  display: flex;
}
.statics-info-li {
  margin-right: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
  justify-content: center;
  text-align: left;
  .title {
    font-size: 15px;
    margin-right: 2px;
    text-align: left;
    // width: 7em;
    display: inline-block;
  }
  .content{
    text-align: left;
    display: inline-block;
    margin-right: 2px;
    color: $menuActive;
  }
}
</style>
